<?php

namespace App\Repositories\Services;

use App\Lib\Tool\Pwd;
use App\Lib\Tool\Ustring;
use App\Repositories\Contracts\MemberRepository;
use App\Repositories\Eloquent\Api\MemberInfoModel;
use App\Repositories\Eloquent\Api\MemberModel;
use App\Repositories\Eloquent\Api\MemberOnlineModel;
use App\Task\Api\Address;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Task\TaskManager;
use EasySwoole\Session\Session;

class Member implements MemberRepository
{
    use Singleton;
    public $member;
    public $status;
    public $msg;
    public $memberModel;
    public $memberOnlineModel;

    // 错误信息
    public $errors = array(
        0 => '系统异常',
        1 => '登录成功',
        2 => '用户名或密码不正确',
        3 => '登录非法',
        4 => 'ip有变化',
        5 => '您尚未登录或登录已超时',
        6 => '用户名或密码错误',
        7 => '您的帐号已被禁用',
        8 => '登录超时',
        9 => '此帐号已登录，不能重复登录',
        110 => '用户名错误',
        111 => '密码错误',
        120 => '系统解码错误',
        130 => '图形验证码错误',
    );
    function __construct()
    {
       $this->memberModel = new MemberModel();
       $this->memberInfoModel = new MemberInfoModel();
       $this->memberOnlineModel = new MemberOnlineModel();
    }

    public function checkLogin($token = '')
    {
        $this->status = 0;
        $memberlineObj = $this->memberOnlineModel->getItemByKey($token);
        if(empty($memberlineObj)){
            return $this->returnError(5);
        }
        //超时
        if(time() - $memberlineObj->active_time > USER_SESSION_TIME_OUT){
            //$this->memberOnlineModel->delByMemberId($memberlineObj->id_user);  可以删除也可以不删除  删除之后之前的登录信息就没有记录了 不能保证一个用户一条数据
            return $this->returnError(8);
        }
        if($memberlineObj->status != 0){
            return $this->returnError(7);
        }
        //更新最后活动时间
        $this->memberOnlineModel->setOnlineActiveTime($memberlineObj->id_user);
        //设置登录会员信息
        $this->member = $this->memberModel->get($memberlineObj->id_user);
        $this->status = 1;
        return $this->returnError(1,$this->member->toArray());

    }



    public function login(string $account='',int $type = 0,array $info = [],string $ip)
    {
        $device = $info['device'];
        $idfa = $info['idfa'];
        $memberObj = $this->memberModel->getItemByAccount($account);
        if(empty($memberObj)){ //注册
            $acode = Pwd::getAcode();
            $memberItem['account'] = $account;
            $memberItem['password'] = Pwd::getPass($account,$acode);
            $memberItem['openid'] = $account;
            $memberItem['acode'] = $acode;
            $memberItem['type'] = $type;
            $memberId = $this->memberModel->addItem($memberItem);
            $memberObj = $this->memberModel->getObjById($memberId);
            $info['id_user'] = $memberId;
            $info['last_login_time'] = time();
            unset($info['device']);
            unset($info['idfa']);
            $this->memberInfoModel->addItem($info);
        }else{
            if($memberObj->status != 1){
                return $this->returnError(7);
            }
            $infoItem['last_login_time'] = time();
            $this->memberInfoModel->updateItem($infoItem,['id_user'=>$memberObj->id]);
        }

        $login_key = $this->loginSuccess($memberObj,$ip,$device,$idfa);
        $this->status = 1;
        return $this->returnError(1,$login_key);

    }

    //登录成功后的操作
    public function loginSuccess($memberObj,$_clientIp,$device,$idfa){
        //设置session 信息
        $login_key = $this->getLoginKey($memberObj->id,$_clientIp);
        //单点登录操作
        $count = $this->memberOnlineModel->getCountByMemberId($memberObj->id);
        //注销登录
        if($count > 0){
            $this->memberOnlineModel->delByMemberId($memberObj->id);
        }
        $item['id_user'] =  $memberObj->id;
        $item['device'] =  $device;
        $item['idfa'] =  $idfa;
        $item['ip'] = $_clientIp;
        $item['login_key'] = $login_key;
        $item['active_time'] = time();
        $item['add_date'] = date('Ymd');
        $this->memberOnlineModel->addItem($item);

        //异步获取用户登录地址
        $task = TaskManager::getInstance();
        $task->async(new Address($item));
        //查询用户vip 是否到期  到期后处理
        return $login_key;
    }

    public function logout(int $memberId = 0)
    {
        $this->memberOnlineModel->delByMemberId($memberId);
    }


    public function __set($name, $value) {
        $this->$name=$value;
    }
    public function __get($name) {
        return $this->$name;
    }

    public function returnError(int $index = 0,$login_key = '') {
      return [$this->status,$this->errors[$index],$login_key];
    }

    protected function getLoginKey($uid,$ip) {
        return substr(md5(microtime(true) . $uid . $ip . Ustring::randString(8)), 0, 20);
    }

}